package appx.craft.droid.uc;

import java.util.LinkedList;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import appx.craft.droid.R;
import appx.craft.droid.bean.FeedBean;
import appx.craft.droid.stricky.StickyListHeadersAdapter;
import appx.craft.droid.ui.onFeedCommentClickListner;
import appx.craft.droid.utils.Constance;
import appx.craft.droid.utils.Log;
import appx.craft.droid.utils.UtilityHelper;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;


public class ProfileAdapter extends BaseAdapter implements
		StickyListHeadersAdapter {

	private final static String TAG = FeedAdapter.class.getCanonicalName();

	private Context mContext;
	private LayoutInflater inflater;
	public static LinkedList<FeedBean> mFeedMessageList;
	private ImageLoader mAdapterLoader;
	private DisplayImageOptions mAdapterOptions;
	private Handler mLikeHandler = new Handler();
	private onFeedCommentClickListner mCommentCallback;
	public static boolean FlagIsUploaded;
	IHeaderListener mHeaderUpdateCallback;

	public ProfileAdapter(Context context, final ImageLoader mImageLoader,
			final DisplayImageOptions mDisplayOption) {
		mContext = context;
		mCommentCallback = (onFeedCommentClickListner) mContext;
		mHeaderUpdateCallback = (IHeaderListener)mContext;
		inflater = LayoutInflater.from(context);
		mFeedMessageList = new LinkedList<FeedBean>();
		mAdapterLoader = mImageLoader;
		mAdapterOptions = mDisplayOption;
	}

	public void clearFeedList() {

		if (mFeedMessageList != null) {

			if (!mFeedMessageList.isEmpty()) {
				mFeedMessageList.clear();
			}

			// notified List view with new Feed List message
			notifyDataSetChanged();
		}
	}

	public synchronized void addNewFeedItem(final FeedBean mTempBean) {

		if (mFeedMessageList != null) {
			mFeedMessageList.add(mTempBean);
			notifyDataSetChanged();
		}
	}

	public void addFirstFeed(final FeedBean mTempBean) {

		if (mFeedMessageList != null) {
			mFeedMessageList.addFirst(mTempBean);
			notifyDataSetChanged();
		}

	}

	public void updateFeed(final FeedBean mUpdateBean, int location) {
		if (mFeedMessageList != null) {
			mFeedMessageList.set(location, mUpdateBean);
		}
	}

	public void addNewFeedAtPosition(final FeedBean mTempBean, int position) {

	}

	@Override
	public int getCount() {
		return mFeedMessageList.size();
	}

	@Override
	public Object getItem(int position) {
		return mFeedMessageList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@SuppressWarnings("deprecation")
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		
		convertView = null;
		
		final ViewHolder holder;

		final FeedBean mFeedTempBean = mFeedMessageList.get(position);

		final String strType = mFeedTempBean.getTypeID();
		
		holder = new ViewHolder();
		
		if (strType.equalsIgnoreCase(Constance.VIEW_PROFILE_ICONS)) {
			convertView = inflater.inflate(R.layout.row_item_settings, parent,
					false);
			
			holder.imagview_profile_settings = (ImageView)convertView.findViewById(R.id.imagview_profile_settings);
			
			
		} else if (strType.equalsIgnoreCase(Constance.VIEW_DOWNLOAD)) {

			convertView = inflater.inflate(R.layout.test_list_item_layout,
					parent, false);

			holder.imageview_profile = (ImageView) convertView
					.findViewById(R.id.imageview_profile);

			holder.textView_header_title = (TextView) convertView
					.findViewById(R.id.textView_header_title);

			holder.textView_timeonly = (TextView) convertView
					.findViewById(R.id.textView_timeonly);

			holder.textView_Caption = (TextView) convertView
					.findViewById(R.id.textView_caption);

			holder.textView_like_counter = (TextView) convertView
					.findViewById(R.id.textView_like_counter);

			holder.textView_more_comments = (TextView) convertView
					.findViewById(R.id.textView_more_comments);

			holder.imageview_photoshared = (ImageView) convertView
					.findViewById(R.id.imageview_photoshared);

			holder.imageview_tran_overlay = (ImageView) convertView
					.findViewById(R.id.imageview_tran_overlay);

			holder.mProgressBar = (ProgressBar) convertView
					.findViewById(R.id.progress_horizontal);

			holder.btn_like_counter = (ImageView) convertView
					.findViewById(R.id.btn_like_counter);

			// ADDED NEW ITEMS IN THE CASE OF UPLOAD
			holder.imageview_upload_cancel = (ImageView) convertView
					.findViewById(R.id.imageview_upload_cancel);

			holder.imageview_item_delete = (ImageView) convertView
					.findViewById(R.id.imageview_item_delete);

			holder.imageview_photo_overlay = (ImageView) convertView
					.findViewById(R.id.imageview_photo_overlay);

			holder.imageview_item_revert = (ImageView) convertView
					.findViewById(R.id.imageview_item_revert);

		}

		if (mFeedTempBean != null) {

			if (strType.equalsIgnoreCase(Constance.VIEW_PROFILE_ICONS)) {
				
				
				holder.imagview_profile_settings.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						mCommentCallback.onProfileIconClick(position);
					}
				});

			} else if (strType.equalsIgnoreCase(Constance.VIEW_DOWNLOAD)) {
				
					if(position > 2){
						mHeaderUpdateCallback.resetHeaderView(position);	
					}else{
						mHeaderUpdateCallback.resetHeaderView(-1);
					}
					
					holder.imageview_upload_cancel.setVisibility(View.INVISIBLE);
					holder.imageview_item_delete.setVisibility(View.INVISIBLE);
					holder.imageview_photo_overlay.setVisibility(View.INVISIBLE);
					holder.imageview_item_revert.setVisibility(View.INVISIBLE);
	
					holder.imageview_tran_overlay.setVisibility(View.VISIBLE);
	
					// cache image and pull to load image
					mAdapterLoader.displayImage(mFeedTempBean.getFilePath(),
							holder.imageview_photoshared, mAdapterOptions,
							new SimpleImageLoadingListener(){
							boolean result = false;
							int index = 0;
							@Override
							public void onLoadingStarted(String imageUri,
									View view) {
								Log.d(TAG, "onLoadingStarted");
								holder.mProgressBar.setVisibility(View.VISIBLE);
								holder.mProgressBar.setProgress(index);
								new Thread(new Runnable() {

									@Override
									public void run() {

										while (!result) {
											try {

												if (index < 100) {
													holder.mProgressBar
															.setProgress(index);
													Thread.sleep(100);
													index = index + 2;
												} else {
													break;
												}

											} catch (Exception e) {
												e.printStackTrace();
											}

										}

									}
								}).start();
							}
							@Override
							public void onLoadingComplete(String imageUri,
									View view, Bitmap loadedImage) {
								Log.d(TAG, "onLoadingComplete");
								result = true;
								holder.mProgressBar.setProgress(100);
								holder.mProgressBar.setVisibility(View.GONE);
							}
							
							@Override
							public void onLoadingCancelled(String imageUri,
									View view) {
								super.onLoadingCancelled(imageUri, view);
							}
							
							@Override
							public void onLoadingFailed(String imageUri,
									View view, FailReason failReason) {
								String message = null;
								switch (failReason) {
									case IO_ERROR:
										message = "Input/Output error";
										break;
									case OUT_OF_MEMORY:
										message = "Out Of Memory error";
										break;
									case NETWORK_DENIED:
										message = "Downloads are denied";
										break;
									case UNSUPPORTED_URI_SCHEME:
										message = "Unsupported URI scheme";
										break;
									case UNKNOWN:
										message = "Unknown error";
										break;
								}
								Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
							}
					});	
				
	
				holder.imageview_profile.setOnClickListener(new OnClickListener() {
	
					@Override
					public void onClick(View v) {
						mCommentCallback.onProfileIconClick(position);
					}
				});
				holder.textView_header_title.setText(mFeedTempBean.getName());
				holder.textView_timeonly.setText(UtilityHelper
						.extractTimefromDate(mFeedTempBean.getCreatedDateTime()));
	
				holder.imageview_photoshared
						.setOnClickListener(new OnClickListener() {
	
							@Override
							public void onClick(View v) {
								mCommentCallback
										.onStreamPhotoSlidingClick(position);
							}
						});
	
				holder.textView_like_counter.setText(new StringBuilder().append(
						mFeedTempBean.getLikeCounter()).append(" likes"));
				holder.textView_like_counter
						.setOnClickListener(new OnClickListener() {
	
							@Override
							public void onClick(View v) {
								mCommentCallback.onStreamLikerListClick(position);
							}
						});
	
				holder.textView_Caption.setText(mFeedTempBean.getCaptionText());
	
				if (mFeedTempBean.getLikeCounter().equalsIgnoreCase("1")) {
					holder.btn_like_counter
							.setBackgroundDrawable(mContext
									.getResources()
									.getDrawable(
											R.drawable.stream_photo_activity_glyph_likes_pressed));
				} else if (mFeedTempBean.getLikeCounter().equalsIgnoreCase("0")) {
					holder.btn_like_counter.setBackgroundDrawable(mContext
							.getResources().getDrawable(
									R.drawable.stream_photo_activity_glyph_likes));
				}
	
				holder.btn_like_counter.setOnClickListener(new OnClickListener() {
	
					@Override
					public void onClick(View v) {
	
						if (mFeedTempBean.getLikeCounter().equalsIgnoreCase("1")) {
							holder.btn_like_counter
									.setBackgroundDrawable(mContext
											.getResources()
											.getDrawable(
													R.drawable.stream_photo_activity_glyph_likes));
						} else if (mFeedTempBean.getLikeCounter().equalsIgnoreCase(
								"0")) {
							holder.btn_like_counter
									.setBackgroundDrawable(mContext
											.getResources()
											.getDrawable(
													R.drawable.stream_photo_activity_glyph_likes_pressed));
						}
						mLikeHandler.postDelayed(new Runnable() {
	
							@Override
							public void run() {
	
								final FeedBean newFeedBean = new FeedBean();
								newFeedBean.setTypeID(mFeedTempBean.getTypeID());
								newFeedBean.setProfileID(mFeedTempBean
										.getProfileID());
								newFeedBean.setFeedID(mFeedTempBean.getFeedID());
	
								newFeedBean.setCaptionText(mFeedTempBean
										.getCaptionText());
	
								newFeedBean.setDisplayName(mFeedTempBean
										.getDisplayName());
	
								newFeedBean.setName(mFeedTempBean.getName());
	
								newFeedBean.setFilePath(mFeedTempBean.getFilePath());
	
								newFeedBean.setCreatedDateTime(mFeedTempBean
										.getCreatedDateTime());
	
								int likeCounter = Integer.parseInt((mFeedTempBean
										.getLikeCounter().equals("") ? "0"
										: mFeedTempBean.getLikeCounter()));
	
								if (likeCounter == 0) {
									newFeedBean.setLikeCounter(String
											.valueOf(likeCounter + 1));
								} else {
									newFeedBean.setLikeCounter(String.valueOf(0));
								}
	
								mFeedMessageList.set(position, newFeedBean);
	
								notifyDataSetChanged();
							}
						}, 200);
					}
				});
				holder.textView_more_comments
						.setOnClickListener(new OnClickListener() {
	
							@Override
							public void onClick(View v) {
								mCommentCallback.onStreamCommentClick(position);
							}
						});
	
			}
				
		}

		return convertView;
	}

	@Override
	public View getHeaderView(int position, View convertView, ViewGroup parent) {
		
		if(mFeedMessageList.get(position).getTypeID().equals(Constance.VIEW_DOWNLOAD)){
		}
		
		HeaderViewHolder holder;
		if (convertView == null) {
			holder = new HeaderViewHolder();
			convertView = inflater.inflate(R.layout.header, parent, false);

			holder.mView_group_header = (LinearLayout) convertView
					.findViewById(R.id.view_group_header);
			holder.textView_header_timestemp = (TextView) convertView
					.findViewById(R.id.textView_timestemp);

			convertView.setTag(holder);

		} else {

			holder = (HeaderViewHolder) convertView.getTag();
		}
		
		if (position == 0) {
			holder.textView_header_timestemp.setVisibility(View.VISIBLE);
		} else {
			holder.textView_header_timestemp.setVisibility(View.GONE);
			holder.mView_group_header.setVisibility(View.GONE);
		}


		return convertView;
	}

	class HeaderViewHolder {
		LinearLayout mView_group_header;
		TextView textView_header_timestemp;
	}

	class ViewHolder {

		ImageView imagview_profile_settings;
		
		ImageView imageview_upload_cancel;
		ImageView imageview_item_revert;
		ImageView imageview_item_delete;
		ImageView imageview_photo_overlay;

		ImageView imageview_profile;
		TextView textView_header_title;
		TextView textView_timeonly;

		TextView textView_Caption;
		TextView textView_like_counter;
		TextView textView_more_comments;

		ImageView imageview_photoshared;
		ImageView imageview_tran_overlay;
		ProgressBar mProgressBar;
		ImageView btn_like_counter;
		Button btn_stream_comment;

		LinearLayout panel_comment_list;
	}

	@Override
	public long getHeaderId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

}
